<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>选项处理</title>
  </head>
  <body>
    <select name="location" id="selLocation">
      <option value="Sunnyvale-value">Sunnyvale</option>
      <option value="Los Angeles-value">Los Angeles</option>
      <option value="Mountain View-value">Mountain View</option>
      <option value="">China</option>
      <option>Australia</option>
    </select>
    <br>
    <button id="myBtn">选中第几项</button>
    <br>
    <select name="multipleSelect" id="multipleSelect" multiple style="height:100px;width:100px">
        <option value="AAA-VALUE">AAA</option>
        <option value="BBB-VALUE">BBB</option>
        <option value="CCC-VALUE">CCC</option>
        <option value="DDD-VALUE">DDD</option>
        <option value="EEE-VALUE">EEE</option>
    </select>
    <div id="multipleSelectShowMessage"></div>
  </body>
  <script>
    // 1.单选框
    const selLocationDOM = document.getElementById('selLocation');
    selLocationDOM.addEventListener('change',(event)=>{
        console.log('change--');
        const selectedIndex = selLocationDOM.selectedIndex; // 获取选中的选项在options中的索引
        const selectedOption = selLocationDOM.options[selectedIndex] //获取选中的选项
        console.log(`Selected index: ${selectedIndex}\n` + `Selected text: ${selectedOption.text}\n` + `Selected value: ${selectedOption.value}`);
    });
    multipleSelectDOM.options[0].selected = true; //默认选中第一项
    //2.多选框
    const multipleSelectDOM = document.querySelector("#multipleSelect");
    const multipleSelectShowMessageDom = document.getElementById('multipleSelectShowMessage');
    let arr = [];
    multipleSelectDOM.addEventListener('change',function(){
        for (const iterator of  multipleSelectDOM.options) {
            if(iterator.selected){
                arr.push(iterator.value)
            }
        }
        console.log('arr--',arr)
        multipleSelectShowMessageDom.innerHTML = arr.join();
    })
    //3.切换
    const myBtn = document.querySelector('#myBtn');
    myBtn.addEventListener('click',function(){
        console.log('onClick')
        multipleSelectDOM.selectedIndex = 1; //手动修改不会触发 change 事件
    });
  </script>
</html>
